package me.fung.wubi.base.define.value

import me.fung.wubi.base.io.autoReadLines
import java.io.File

class WordFrequency(
    var one: Int = 255,
    var default: Int = 255,
    val map: MutableMap<Word, Int> = HashMap()
) : MutableMap<Word, Int> by map {

    fun loadFromFile(file: File): WordFrequency {
        file.autoReadLines().forEach {
            val list = it.split(' ', '\t')
            //可能含有编码， 后两位当作词和码表，
            val size = list.size
            if (size >= 2) {
                val word = list[size - 2].toWord()
                val freq = list[size - 1].toIntOrNull()
                when (word) {
                    "{.default}".toWord() -> {
                        default = freq ?: default
                    }

                    "{.one}".toWord() -> {
                        one = freq ?: one
                    }

                    else -> {
                        tryPut(word, freq)
                    }
                }
            }
        }
        return this
    }

    fun tryPut(word: Word, freq: Int?) {
        if (freq == null) return
        put(word, freq)
    }

    fun frequencyOf(word: Word): Int {
        return get(word) ?: if (word.length == 1) one else default
    }

    fun max(): Int = this.maxOfOrNull { it.value } ?: default


    fun min(): Int = this.minOfOrNull { it.value } ?: default
}